//
//  YPNetWorking.m
//  网络请求_WYP_测试
//
//  Created by lanou3g on 15/12/15.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPNetWorking.h"

static YPNetWorking *net = nil;
@implementation YPNetWorking
//单例
+(instancetype)shareNetWorking{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        net = [[YPNetWorking alloc]init];
    });
    return net;
}
//获取字典
- (void)getDictWithURL:(NSString *)url dict:(NSDictionary *)dict success:(void (^)(NSDictionary *))success fail:(void (^)(NSError *))fail{
    if (url == nil || ![url isKindOfClass:[NSString class]]) {//判断URL是否为空
        return;
    }
    //开一个线程进行异步请求
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //准备网址
        NSURL *URL = [NSURL URLWithString:url];
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];
        request.HTTPMethod = @"POST";
        //此处发送一定要设置，这个地方把字典封装为json格式
        [request setValue:@"application/jason" forHTTPHeaderField:@"Content-Type"];
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        request.HTTPBody = data;
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            //请求失败
            if (dict.count < 1) {
            NSError *err = [NSError errorWithDomain:@"数据请求为空" code:404 userInfo:nil];
                fail(err);
            }
            //请求成功,回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                success(dict);
            });
        }];
        [dataTask resume];
    });
}


@end
